﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YouDaoNotesCodes.CSharp_highLevel
{
    /// <summary>
    /// lambda表达式：介绍匿名函数-->委托-->lambda表达式
    /// </summary>
    class lambda
    {
        //① ↓↓↓↓↓匿名方法分2步↓↓↓↓↓

        //step01：用delegate定义一个委托
        public delegate int deleFun(int x, int y);

        public void AnonymousMethods()
        {
            //step02：把一个方法赋值给委托
            deleFun dFun = delegate(int x, int y) { return x + y; };//这里~
            Console.WriteLine(dFun.Invoke(5, 6));
        }

        //② ↓↓↓↓↓委托分3步↓↓↓↓↓

        //step01：用delegate定义一个委托
       // public delegate int deleFun(int x, int y);
        //step02：声明一个方法来对应委托
        public static int Add(int x, int y)
        {
            return x + y;
        }
        public void delegateMethod()
        {
            //step03：用这个方法来实例化这个委托
            deleFun dFun = new deleFun(Add);
            Console.WriteLine(dFun.Invoke(5, 6));//这里~
        }

        //③ ↓↓↓↓↓lambda表达式简化了第2步↓↓↓↓↓

        //step01：用delegate定义一个委托
      //  public delegate int deleFun(int x, int y);

        public void lambdaMethod()
        {
            //step02：把一个方法赋值给委托  
            deleFun dFun = (x, y) => { return x + y; };//这里~
            Console.WriteLine(dFun.Invoke(5, 6));
        }

        //④ 泛型委托只需要一步
        public void GenericDelegate()
        {
            //step01：定义泛型委托 并把一个方法赋值给委托  
            Func<int, int, int> dFun = (x, y) => { return x + y; };
            //Func<int, int, int> fun = new Func<int, int, int>(Add);//或者这样 

            Console.WriteLine(dFun.Invoke(5, 6));
        }
    }
}
